package bluetooth;


import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.telecom.TelecomManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

public class PhoneService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public void onCreate() {

        System.out.println("onCreate");
        //1.获取telephone的实例
        TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);

        //2.注册电话的监听
        tm.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


    public class MyPhoneStateListener extends PhoneStateListener {

        //当电话设置状态发生改变的时候调用
        @Override
        public void onCallStateChanged(int state, String phoneNumber) {
            System.out.println("state==>"+state);
            System.out.println("phoneNumber==>"+phoneNumber);

            Intent intent2 = new Intent(BluetoothLeService.ACTION_CALL);

            //具体判断下电话得状态
            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    System.out.println("停止");
//                    Toast.makeText(PhoneService.this,"电话挂断",Toast.LENGTH_LONG).show();
                    intent2.putExtra(BluetoothLeService.ACTION_CALL, TelephonyManager.CALL_STATE_IDLE+"");
                    sendBroadcast(intent2);
                    break;

                case TelephonyManager.CALL_STATE_OFFHOOK://接听状态
                    System.out.println("开始录");
                    Toast.makeText(PhoneService.this,"电话接通",Toast.LENGTH_LONG).show();
                    intent2.putExtra(BluetoothLeService.ACTION_CALL, TelephonyManager.CALL_STATE_OFFHOOK+"");
                    sendBroadcast(intent2);
                    break;


                case TelephonyManager.CALL_STATE_RINGING://电话响铃状态


//                    System.out.println("准备一个录音机");
                    Toast.makeText(PhoneService.this,"正在响铃"+phoneNumber,Toast.LENGTH_LONG).show();
                    intent2.putExtra(BluetoothLeService.ACTION_CALL, TelephonyManager.CALL_STATE_RINGING+"");
                    sendBroadcast(intent2);
                    break;

                default:


                    break;


            }


            super.onCallStateChanged(state, phoneNumber);
        }
    }


}
